/**
 * Express Web框架的应用模块
 * 1.导入所需的模块
 * 2.导入路由模块
 * 3.应用层的中间件
 * 4.定义路由模块
 * 5.导出Express应用实例
 */
//1.导入所需的模块

//导入Express模块
var express = require("express");
//导入node.js的Path模块
var path = require("path");
//导入Express的Cookie模块
var cookieParser = require("cookie-parser");
//导入日志模块
var logger = require("morgan");

// 导入Session模块
const session = require("express-session");
// 导入Session存储支持模块SQLite
const SQLiteStore = require("connect-sqlite3")(session);

//导入Swagger-ui-express模块
const swaggerUi = require("swagger-ui-express");
//导入swagger-jsdoc模块
const swaggerJsdoc = require("swagger-jsdoc");
//导入初始化数据库中间件
const initSqliteDB = require("./controller/init");

//2.导入路由模块

//导入默认路由
var indexRouter = require("./routes/index");
//导入用户路由
var usersRouter = require("./routes/users");
//导入书籍路由
const booksRouter = require("./routes/books");

//生成应用实例“app”
var app = express();

//3.应用层的中间件
//开发日志
app.use(logger("dev"));
//Json解析
app.use(express.json());
//url编码
app.use(express.urlencoded({ extended: false }));
//Cookie
app.use(cookieParser());
//静态资源
app.use(express.static(path.join(__dirname, "public")));

//中间件：swagger
const options = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "我的藏书馆接口",
      version: "1.0.0",
    },
  },
  apis: [path.join(__dirname, "./routes/*.js")],
};

const openapiSpecification = swaggerJsdoc(options);
app.use("/dev-api", swaggerUi.serve, swaggerUi.setup(openapiSpecification));

//中间件：数据库初始化
app.use(initSqliteDB());

//Express中的session支持
// app.use(initSqliteDB());

/**
 * Express中的Session支持
 * 1. npm install express-sesion connect-sqlite3
 * 2. 导入模块
 * 3. 使用Session中间件
 * 4. Session存储：SQLiteStore
 */

app.use(
  session({
    secret: "sdfsdfsf@#@$234", //session的salt
    resave: false, //session工作方式：session是否重新保存
    saveUninitialized: false, //session工作方式：未初始化的session是否保存
    cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 }, // sessionID在客户端cookie中保存1周
    store: new SQLiteStore({
      dir: "./data",
      db: "mylibrary.db",
    }),
  })
);

//4.定义路由模块
//默认路由 -> /
app.use("/", indexRouter);
//用户路由 -> /users
app.use("/users", usersRouter);
//书籍路由 -> /books
app.use("/books", booksRouter);

//5.导出Express应用实例
module.exports = app;
